/**
 * 软件著作权：东方汇创
 *
 * 系统名称：  qb5&activiti
 *
 * 文件名称：  GeneralBusinessProcessController.java
 *
 * 功能描述：  通用流程业务表Controller
 * 
 * 版本历史：
 * 
 * 2016-12-06   1.0.0版 （龙色波）（创建文件）
 */
package com.dfhc.wk.generalbusinessprocess.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.quickbundle.base.beans.factory.RmBeanFactory;
import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.login.RmUserVo;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmVoHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.ActivitiService;
import com.dfhc.pub.service.IExtGeneralBusinessProcessService;
import com.dfhc.pub.service.PubParamService;
import com.dfhc.util.CryptoHelper;
import com.dfhc.util.DateUtil;
import com.dfhc.util.StringHelper;
import com.dfhc.wk.dataset.service.DataSetService;
import com.dfhc.wk.formtemplate.service.FormTemplateService;
import com.dfhc.wk.formtemplate.vo.FormTemplateVo;
import com.dfhc.wk.generalbusinessprocess.IGeneralBusinessProcessConstants;
import com.dfhc.wk.generalbusinessprocess.service.GeneralBusinessProcessService;
import com.dfhc.wk.generalbusinessprocess.vo.AuditInfoVo;
import com.dfhc.wk.generalbusinessprocess.vo.GeneralBusinessProcessVo;
import com.dfhc.wk.processdataitems.vo.TaskForListVo;
import com.dfhc.wk.tasknodeextconf.service.TaskNodeExtConfService;
/**
 * list                  /generalbusinessprocess
 * insert page      GET  /generalbusinessprocess/insert
 * insert action    POST /generalbusinessprocess/insert
 * update page      GET  /generalbusinessprocess/update/{id}
 * update action    POST /generalbusinessprocess/update
 * delete action    POST /generalbusinessprocess/delete
 * detail                /generalbusinessprocess/detail/{id}

 * reference             /generalbusinessprocess/reference
 * import page      GET  /generalbusinessprocess/import
 * import action    POST /generalbusinessprocess/import
 * export custom    GET  /generalbusinessprocess/export
 * export action    POST /generalbusinessprocess/export
 */

/**
 * 通用流程业务表 Controller
 * 
 * @author 龙色波
 * @see 参见的类
 */
@Controller
@RequestMapping(value = "/generalbusinessprocess")
public class GeneralBusinessProcessController implements IGeneralBusinessProcessConstants {
	//private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    /**
     * 通用流程业务表服务
     */
    private GeneralBusinessProcessService generalBusinessProcessService;
    @Autowired
   	/**
   	 * 任务节点扩展配置服务
   	 */
   	private TaskNodeExtConfService taskNodeExtConfService;
       @Autowired
   	/**
   	 * Activiti工作流服务封装
   	 */
   	private ActivitiService activitiService;
       @Autowired
   	/**
   	 * 表单模板服务
   	 */
   	private FormTemplateService formTemplateService;
    @Autowired
    private DataSetService dataSetService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private PubParamService pubParamService;
    @Autowired
    private FormService formService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    IdentityService identityService;
    
    /**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> searchPara = getQueryCondition(request);  //从request中获得查询条件
	        RmPageVo pageVo = RmJspHelper.transctPageVo(request, generalBusinessProcessService.getCount(searchPara));
	        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
	        List<GeneralBusinessProcessVo> beans = generalBusinessProcessService.list(searchPara, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
	        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
	        model.addAttribute(REQUEST_QUERY_CONDITION, searchPara);
	        model.addAttribute(REQUEST_BEANS, beans);  //把结果集放入request
	        model.addAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));  //回写表单
	        return "/activiti/wk/generalbusinessprocess/listGeneralBusinessProcess";
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }        
    }
   
    
    /**
     * 从页面表单获取信息注入vo，并插入单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> insert(HttpServletRequest request, @Valid GeneralBusinessProcessVo vo) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
	        generalBusinessProcessService.insert(vo);  //插入单条记录
	        Map<String, Object> result = new HashMap<String, Object>();
	        result.put(ISystemConstant.AJAX_BEAN, vo);
	        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        result.put(ISystemConstant.AJAX_MESSAGE, "新增成功: " + vo.getId());
	        return result;
	    }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }        
    }
    
    /**
     * 从页面表单获取信息注入vo，并修改单条记录
     * @param request 请求对象
     * @param vo 值对象
     * @param errors Ajax错误对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "update", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> update(HttpServletRequest request, @Valid GeneralBusinessProcessVo vo) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
	        generalBusinessProcessService.update(vo);  //更新单条记录
	        Map<String, Object> result = new HashMap<String, Object>();
	        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        result.put(ISystemConstant.AJAX_MESSAGE, "修改成功: " + vo.getId());
	        return result;
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }	        
    }
    /**
     * 根据id获取单条记录
     * @param request 请求对象
     * @param vo 值对象
     * @param
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "get/{id}/{dateTime}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> get(@PathVariable("id") String id, HttpServletRequest request) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        GeneralBusinessProcessVo bean = generalBusinessProcessService.get(id);
	        Map<String, Object> result = new HashMap<String, Object>();
	        if(bean==null){
	            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
	            result.put(ISystemConstant.AJAX_MESSAGE, "记录没找到(id:"+id+")!");
	            return result;
	        }
	        
	        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        result.put(ISystemConstant.AJAX_BEAN, bean);
	        return result;	
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }        
    }    
    /**
     * 从页面的表单获取单条记录id并删除，如request.id为空则删除多条记录（request.ids）
     * @param request http请求对象
     * @param redirectAttributes 重定向属性
     * @return 返回列表页面
     * @throws Exception 
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public String delete(HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        int deleteCount = 0;  //定义成功删除的记录数
	        String id = request.getParameter(REQUEST_ID);
	        if(id != null && id.length() > 0) {
	            deleteCount = generalBusinessProcessService.delete(new String(id));
	        } else {
	            String[] ids = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS); //从request获取多条记录id
	            if (ids != null && ids.length != 0) {
	                deleteCount += generalBusinessProcessService.delete(ids);  //删除多条记录
	            }
	        }
	        redirectAttributes.addFlashAttribute("message", "删除成功: " + deleteCount);
	        return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess");
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }        
    }
    /**
     * 从页面的表单获取单条记录id并删除，如request.id为空则删除多条记录（request.ids）
     * @param request http请求对象
     * @param redirectAttributes 重定向属性
     * @return 返回列表页面
     */
    @RequestMapping(value = "deleteAjax", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteAjax(HttpServletRequest request, RedirectAttributes redirectAttributes) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	    	Map<String, Object> result = new HashMap<String, Object>();
	        int deleteCount = 0;  //定义成功删除的记录数
	        String id = request.getParameter(REQUEST_ID);
	        if(id != null && id.length() > 0) {
	            deleteCount = generalBusinessProcessService.delete(new String(id));
	        } else {
	            String[] ids = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS); //从request获取多条记录id
	            if (ids != null && ids.length != 0) {
	                deleteCount += generalBusinessProcessService.delete(ids);  //删除多条记录
	            }
	        }
	        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        result.put(ISystemConstant.AJAX_MESSAGE, "删除成功: " + deleteCount);
	        return result;
	    }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
	    }        
    }
   /**
     * 从页面的表单获取单条记录id并逻辑删除，如request.id为空则删除多条记录（request.ids）
     * @param request http请求对象
     * @param redirectAttributes 重定向属性
     * @return 返回列表页面
 * @throws Exception 
     */
    @RequestMapping(value = "logicDelete", method = RequestMethod.POST)
    public String deleteLogic(HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        int deleteCount = 0;  //定义成功删除的记录数
	        String id = request.getParameter(REQUEST_ID);
	        if(id != null && id.length() > 0) {
	            deleteCount = generalBusinessProcessService.deleteLogic(request,new String(id));
	        } else {
	            String[] ids = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS); //从request获取多条记录id
	            if (ids != null && ids.length != 0) {
	                deleteCount += generalBusinessProcessService.deleteLogic(request,ids);  //删除多条记录
	            }
	        }
	        redirectAttributes.addFlashAttribute("message", "删除成功: " + deleteCount);
	        return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess");
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
          }        
    }
    /**
     * 从页面的表单获取单条记录id，并察看这条记录的详细信息
     * @param id 待删除的id
     * @param model 模型
     * @request 请求对象
     * @return 返回详细信息页面
     */
    @RequestMapping(value = "detail/{id}")
    public String detail(@PathVariable("id") String id, Model model, HttpServletRequest request) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        GeneralBusinessProcessVo bean = generalBusinessProcessService.get(id);
	        model.addAttribute(REQUEST_BEAN, bean);  //把vo放入request
	        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
	            model.addAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
	        }
	        return "/activiti/wk/generalbusinessprocess/detailGeneralBusinessProcess";
	    }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
	    }        
    }

    /**
     * 参照信息查询，带简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 返回参照列表页面
     */
    @RequestMapping(value = "reference")
    public String reference(Model model, HttpServletRequest request) {
        list(model, request);
        model.addAttribute(REQUEST_REFERENCE_INPUT_TYPE, request.getParameter(REQUEST_REFERENCE_INPUT_TYPE));  //传送输入方式,checkbox或radio
        return "/activiti/wk/generalbusinessprocess/util/referenceGeneralBusinessProcess";
    }

    /**
     * 跳转到导入页
     * @param model 模型
     * @return 返回导入页
     */
    @RequestMapping(value = "import", method = RequestMethod.GET)
    public String importDataForm(Model model) {
        return "/activiti/wk/generalbusinessprocess/importGeneralBusinessProcess";
    }
    
    /**
     * 执行导入
     * @param model 模型
     * @return 返回导入页面
     */
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importData(Model model) {
        model.addAttribute("isSubmit", "1");
        return "/activiti/wk/generalbusinessprocess/importGeneralBusinessProcess";
    }
    
    /**
     * 定制导出
     * @param model 模型
     * @return 返回导出页面
     */
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public String exportCustomForm(Model model) {
        return "/activiti/wk/generalbusinessprocess/exportGeneralBusinessProcess_custom";
    }
    
    /**
     * 执行导出
     * @param model 模型
     * @return 返回导出xls页面
     */
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportData(Model model) {
        return "/activiti/wk/generalbusinessprocess/exportGeneralBusinessProcess_excel";
    }

    /**
     * 从request中获得查询条件
     * @param request http请求对象
     * @return 条件Map
     */
    @SuppressWarnings("unchecked")
	public static Map<String, Object> getQueryCondition(HttpServletRequest request) {
        Map<String, Object> searchMap = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            searchMap = (Map<String, Object>)request.getAttribute(REQUEST_QUERY_CONDITION);
        } else {
           searchMap = new HashMap<String, Object>();
           searchMap.put("id", request.getParameter("id"));
           searchMap.put("procDefId", request.getParameter("procDefId"));
           searchMap.put("procInstId", request.getParameter("procInstId"));
           searchMap.put("procName", request.getParameter("procName"));
           searchMap.put("procKey", request.getParameter("procKey"));
           searchMap.put("initiator", request.getParameter("initiator"));
           searchMap.put("initiatorId", request.getParameter("initiatorId"));
           searchMap.put("sendOrganizationDepartment", request.getParameter("sendOrganizationDepartment"));
           searchMap.put("initiatorOrganizationId", request.getParameter("initiatorOrganizationId"));
           searchMap.put("initiatorTime", request.getParameter("initiatorTime"));
           searchMap.put("businessType", request.getParameter("businessType"));
           searchMap.put("businessAttribute70", request.getParameter("businessAttribute70"));
           searchMap.put("businessAttribute69", request.getParameter("businessAttribute69"));
           searchMap.put("businessAttribute68", request.getParameter("businessAttribute68"));
           searchMap.put("businessAttribute67", request.getParameter("businessAttribute67"));
           searchMap.put("businessAttribute66", request.getParameter("businessAttribute66"));
           searchMap.put("businessAttribute65", request.getParameter("businessAttribute65"));
           searchMap.put("businessAttribute64", request.getParameter("businessAttribute64"));
           searchMap.put("businessAttribute63", request.getParameter("businessAttribute63"));
           searchMap.put("businessAttribute62", request.getParameter("businessAttribute62"));
           searchMap.put("businessAttribute61", request.getParameter("businessAttribute61"));
           searchMap.put("businessAttribute60", request.getParameter("businessAttribute60"));
           searchMap.put("businessAttribute59", request.getParameter("businessAttribute59"));
           searchMap.put("businessAttribute58", request.getParameter("businessAttribute58"));
           searchMap.put("businessAttribute57", request.getParameter("businessAttribute57"));
           searchMap.put("businessAttribute56", request.getParameter("businessAttribute56"));
           searchMap.put("businessAttribute55", request.getParameter("businessAttribute55"));
           searchMap.put("businessAttribute54", request.getParameter("businessAttribute54"));
           searchMap.put("businessAttribute53", request.getParameter("businessAttribute53"));
           searchMap.put("businessAttribute52", request.getParameter("businessAttribute52"));
           searchMap.put("businessAttribute51", request.getParameter("businessAttribute51"));
           searchMap.put("businessAttribute50", request.getParameter("businessAttribute50"));
           searchMap.put("businessAttribute49", request.getParameter("businessAttribute49"));
           searchMap.put("businessAttribute48", request.getParameter("businessAttribute48"));
           searchMap.put("businessAttribute47", request.getParameter("businessAttribute47"));
           searchMap.put("businessAttribute46", request.getParameter("businessAttribute46"));
           searchMap.put("businessAttribute45", request.getParameter("businessAttribute45"));
           searchMap.put("businessAttribute44", request.getParameter("businessAttribute44"));
           searchMap.put("businessAttribute43", request.getParameter("businessAttribute43"));
           searchMap.put("businessAttribute42", request.getParameter("businessAttribute42"));
           searchMap.put("businessAttribute41", request.getParameter("businessAttribute41"));
           searchMap.put("businessAttribute40", request.getParameter("businessAttribute40"));
           searchMap.put("businessAttribute39", request.getParameter("businessAttribute39"));
           searchMap.put("businessAttribute38", request.getParameter("businessAttribute38"));
           searchMap.put("businessAttribute37", request.getParameter("businessAttribute37"));
           searchMap.put("businessAttribute36", request.getParameter("businessAttribute36"));
           searchMap.put("businessAttribute35", request.getParameter("businessAttribute35"));
           searchMap.put("businessAttribute34", request.getParameter("businessAttribute34"));
           searchMap.put("businessAttribute33", request.getParameter("businessAttribute33"));
           searchMap.put("businessAttribute32", request.getParameter("businessAttribute32"));
           searchMap.put("businessAttribute31", request.getParameter("businessAttribute31"));
           searchMap.put("businessAttribute30", request.getParameter("businessAttribute30"));
           searchMap.put("businessAttribute29", request.getParameter("businessAttribute29"));
           searchMap.put("businessAttribute28", request.getParameter("businessAttribute28"));
           searchMap.put("businessAttribute27", request.getParameter("businessAttribute27"));
           searchMap.put("businessAttribute26", request.getParameter("businessAttribute26"));
           searchMap.put("businessAttribute25", request.getParameter("businessAttribute25"));
           searchMap.put("businessAttribute24", request.getParameter("businessAttribute24"));
           searchMap.put("businessAttribute23", request.getParameter("businessAttribute23"));
           searchMap.put("businessAttribute22", request.getParameter("businessAttribute22"));
           searchMap.put("businessAttribute21", request.getParameter("businessAttribute21"));
           searchMap.put("businessAttribute20", request.getParameter("businessAttribute20"));
           searchMap.put("businessAttribute19", request.getParameter("businessAttribute19"));
           searchMap.put("businessAttribute18", request.getParameter("businessAttribute18"));
           searchMap.put("businessAttribute17", request.getParameter("businessAttribute17"));
           searchMap.put("businessAttribute16", request.getParameter("businessAttribute16"));
           searchMap.put("businessAttribute15", request.getParameter("businessAttribute15"));
           searchMap.put("businessAttribute14", request.getParameter("businessAttribute14"));
           searchMap.put("businessAttribute13", request.getParameter("businessAttribute13"));
           searchMap.put("businessAttribute12", request.getParameter("businessAttribute12"));
           searchMap.put("businessAttribute11", request.getParameter("businessAttribute11"));
           searchMap.put("businessAttribute10", request.getParameter("businessAttribute10"));
           searchMap.put("businessAttribute9", request.getParameter("businessAttribute9"));
           searchMap.put("businessAttribute8", request.getParameter("businessAttribute8"));
           searchMap.put("businessAttribute7", request.getParameter("businessAttribute7"));
           searchMap.put("businessAttribute6", request.getParameter("businessAttribute6"));
           searchMap.put("businessAttribute5", request.getParameter("businessAttribute5"));
           searchMap.put("businessAttribute4", request.getParameter("businessAttribute4"));
           searchMap.put("businessAttribute3", request.getParameter("businessAttribute3"));
           searchMap.put("businessAttribute1", request.getParameter("businessAttribute1"));
           searchMap.put("businessAttribute2", request.getParameter("businessAttribute2"));
           searchMap.put("delete_flag",ISystemConstant.DICTIONARY_RM_YES_NOT_0);
        }
        return searchMap;
    }
    /**
     * 待办任务列表
     *
     * @param leave
     */
    @RequestMapping(value = "taskList")
    @Transactional(readOnly = true)
    public String taskList(HttpServletRequest request) {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        String userId = RmProjectHelper.getRmUserId(request);
	        List<Task> results = generalBusinessProcessService.findTodoTasks(userId);
	    	RmPageVo pageVo = RmJspHelper.transctPageVo(request, results.size());
	  	  	List<Task> list = new ArrayList<Task>();
	  	  	int totalNum = pageVo.getStartIndex()-1+pageVo.getPageSize();
	  	  	if(pageVo.getStartIndex()+pageVo.getPageSize()>pageVo.getRecordCount()){
	  	  		totalNum = pageVo.getRecordCount();
	  	  	}
	  	  	for(int i=pageVo.getStartIndex()-1; i<totalNum; i++){
	  	  		list.add(results.get(i));
	  	  	}
	  	  	request.setAttribute("beans", list);
	  	  	//如果传了jsp url ，则跳转到jsp url页面
	  	  	String jspUrl = request.getParameter(ISystemConstant.PREDEFINED_JSP_URL);
	  	  	if(StringHelper.isEmpty(jspUrl)){
	  	  		return "/activiti/wk/listGenneralTask";
	  	  	}else{
	  	  		return jspUrl;
	  	  	}
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }  	  	
    }
    /**
     * 签收任务
     * @throws Exception 
     */
    @RequestMapping(value = "claim")
    public String claim(  HttpServletRequest request, RedirectAttributes redirectAttributes,HttpServletResponse response) throws Exception {
    	boolean bLock = false;
    	String taskId = request.getParameter(REQUEST_ID);
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));    
	        String userId = RmProjectHelper.getRmUserId(request);
	        //如果传个性化服务id		  	
	  		String serviceBeanId = request.getParameter(ISystemConstant.PREDEFINED_SERVICE_BEAN_ID);
	  		if(!StringHelper.isEmpty(serviceBeanId)){
	  			IExtGeneralBusinessProcessService  generalBusinessService = (IExtGeneralBusinessProcessService) RmBeanFactory.getBean(serviceBeanId);
	 			generalBusinessService.doClaim(request, response);  			
	  		}else{
	  			taskService.claim(taskId, userId);  			
	  		}
	
	        String jspUrl = request.getParameter(ISystemConstant.PREDEFINED_JSP_URL);
	        if(StringHelper.isEmpty(jspUrl)){
		        redirectAttributes.addFlashAttribute("message", "任务已签收");
		        return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
	        }else{
	        	return jspUrl.trim();
	        }
        }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }	        
    }
    /**
     * 办理任务  创任务id或流程id  启动时，应传流程id
     * @throws Exception 
     */
    @RequestMapping(value = "view")
    public String showTaskView(HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
    	boolean bLock = false;
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));  
	    	Map<String, Object> taskDataMap = new HashMap<String, Object>();
	        List<TaskForListVo> taskForListVos = null;
	        String taskId = request.getParameter(ISystemConstant.PREDEFINED_TASK_ID);
	        //如果任务id为空，则尝试根据流程id获取第一个节点id
	        String processDefinitionId ="";
	        processDefinitionId = request.getParameter(ISystemConstant.PREDEFINED_PROCESS_DEFINITION_ID);
	        //预定义参数：流程定义id
	        taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_DEFINITION_ID, processDefinitionId);
	        request.setAttribute(ISystemConstant.AJAX_BEAN, taskDataMap);
	        if(StringHelper.isEmpty(taskId)){
	        	if(StringHelper.isEmpty(processDefinitionId)){
	        		redirectAttributes.addFlashAttribute("message", "流程定义id和任务id不能同时为空!");
		        	//出错时，跳转url
		        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
		        	if(StringHelper.isEmpty(errorJspUrl)){
		        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
		        	}else{
		        		return errorJspUrl;
		        	}	
	        	}else{
	        		taskForListVos = activitiService.getTaskNodeListByProDefId(processDefinitionId);
	        		if(CollectionUtils.isEmpty(taskForListVos)){
	        			redirectAttributes.addFlashAttribute("message", "流程下无任务节点!");
			        	//出错时，跳转url
			        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
			        	if(StringHelper.isEmpty(errorJspUrl)){
			        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
			        	}else{
			        		return errorJspUrl;
			        	}	
	        		}
	        		taskId = taskForListVos.get(0).getTaskId();
	        	}
	        	
	        }

	        Task task = null;
	        if(StringHelper.isEmpty(processDefinitionId)){
	        	task = (Task) taskService.createTaskQuery().taskId(taskId).singleResult();
	        }else{
	        	List<Task> tasks = activitiService.findTaskListByKey(processDefinitionId,taskId);
	        	if(!CollectionUtils.isEmpty(tasks)){
	        		task = tasks.get(0); 
	        	}
	        }
	        
	        String procInstId = task ==null?"":task.getProcessInstanceId();
	        String taskDefinitionKey = task==null?taskId:task.getTaskDefinitionKey();
	        processDefinitionId = task==null?processDefinitionId:task.getProcessDefinitionId();
	        Map<String, Object> searchMap = new HashMap<String, Object>();
	        searchMap.put("procInstId", procInstId);
	        //流程实例ID不为空
	        if(!StringHelper.isEmpty(procInstId)){
		        List<GeneralBusinessProcessVo> generalBusinessProcessVos = generalBusinessProcessService.list(searchMap, null);
		        if(generalBusinessProcessVos.size()>0){
		        	GeneralBusinessProcessVo generalBusinessProcessVo = generalBusinessProcessVos.get(0);		 
		    		taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_GENERAL_BUSINESS_PROCESSVO,RmVoHelper.getMapFromVo(generalBusinessProcessVo));		    		
		    		//查询子表对应的数据
		    		List<GeneralBusinessProcessVo> generalBusinessProcessVos2 = generalBusinessProcessService.getByParentId(generalBusinessProcessVo.getId());
		    		taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_CHILD_GENERAL_BUSINESS_PROCESSVOS, generalBusinessProcessVos2);
		        }else{
		        	redirectAttributes.addFlashAttribute("message", "根据流程实例id没有找到与之对应的通用流程业务数据!");
		        	//出错时，跳转url
		        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
		        	if(StringHelper.isEmpty(errorJspUrl)){
		        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
		        	}else{
		        		return errorJspUrl;
		        	}
		        }
	        }
	        //如果传个性化服务id		  	
	  		String serviceBeanId = request.getParameter(ISystemConstant.PREDEFINED_SERVICE_BEAN_ID);
	  		if(!StringHelper.isEmpty(serviceBeanId)){
	  			IExtGeneralBusinessProcessService  generalBusinessService = (IExtGeneralBusinessProcessService) RmBeanFactory.getBean(serviceBeanId);
	 			taskDataMap.putAll(generalBusinessService.readTaskData(request));  			
	  		}
	  		//预定义参数：任务id
	  		taskDataMap.put(ISystemConstant.PREDEFINED_TASK_ID, taskId);
	  		//===========end 模板参数============
	  		
	  		//===========begin 查询审核意见=======
	  		if(taskForListVos==null){
	  			taskForListVos = activitiService.getTaskNodeListByProDefId(processDefinitionId);
	  		}
	  		List<AuditInfoVo> auditInfoVos = new ArrayList<AuditInfoVo>();
	  		if(task!=null){
		  		for (TaskForListVo taskForListVo : taskForListVos) {
					if(taskForListVo.getTaskId().equals(taskDefinitionKey)){
						break;
					}
					if(StringHelper.isEmpty(taskForListVo.getIsStart())||ISystemConstant.DICTIONARY_RM_YES_NOT_0.equals(taskForListVo.getIsStart())){
						String taskId2 = generalBusinessProcessService.getTaskIdByTaskDefKey(taskForListVo.getTaskId(),task.getProcessInstanceId());
						if(!StringHelper.isEmpty(taskId2)){
							AuditInfoVo auditInfoVo = new AuditInfoVo();
							List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().processInstanceId(task.getProcessInstanceId()).taskId(taskId2).list();
							for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
								if(ISystemConstant.PREDEFINED_USER_NAME.equals(historicVariableInstance.getVariableName())){
									auditInfoVo.setAuditName(historicVariableInstance.getValue().toString());
								}
								if(ISystemConstant.PREDEFINED_AUDIT_TIME.equals(historicVariableInstance.getVariableName())){
									auditInfoVo.setAuditTime(historicVariableInstance.getValue().toString());
								}
								if(ISystemConstant.PREDEFINED_AUDIT_STATE.equals(historicVariableInstance.getVariableName())){
									auditInfoVo.setAuditState(historicVariableInstance.getValue().toString());
								}
							}
							List<Comment> comments = taskService.getTaskComments(taskId2);
							if(comments!=null && comments.size()>0){
								//审核意见
								auditInfoVo.setAuditOpinion(comments.get(0).getFullMessage());
							}
							auditInfoVos.add(auditInfoVo);
						}
					}
		  		}
		  		
		  		taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_AUDITVOS, auditInfoVos);
	  		}
	  		//===========end 查询审核意见=========
	  		
	  		//===========begin 获取界面模板名称================
//	  		ProcessDefinition processDefine = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
	  	
	  		
	  		//String formTemplateName = activitiService.getTaskFormDataKey(processDefinitionId,taskDefinitionKey);
	  		String formTemplateName="";
	  		
	  		for(TaskForListVo vo:taskForListVos){
	  			if(vo.getTaskId().equals(taskDefinitionKey)){
	  					formTemplateName = vo.getFormKey();
	  					break;
	  			}
	  		}
	  		if(StringHelper.isEmpty(formTemplateName)){
	  			//尝试从当前节点获取属性定义
	  			/*FormDataImpl taskFormData = (FormDataImpl) formService.getTaskFormData(taskId);
	  			if(taskFormData==null||CollectionUtils.isEmpty(taskFormData.getFormProperties())){
	  				redirectAttributes.addFlashAttribute("message", "当前选择的流程定义id:"+processDefinitionId+" 没有找到与之关联的开始表单的key!");
	  				//出错时，跳转url
		        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
		        	if(StringHelper.isEmpty(errorJspUrl)){
		        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
		        	}else{
		        		return errorJspUrl;
		        	}
	  			}
	  			taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_FORMDATALIST, taskFormData.getFormProperties());
	  			
	  			Map<String, Object> map=(Map<String, Object>) taskDataMap.get(ISystemConstant.PREDEFINED_PROCESS_GENERAL_BUSINESS_PROCESSVO);

	  			Map<String, List<Map<String, Object>>> enumBigMap = new HashMap<String, List<Map<String,Object>>>(); 
	    		for (FormProperty formProperty : taskFormData.getFormProperties()) {
	    			//通用业务表流程数据不为空，则填充通用业务表里的值
	    			if(map!=null)
	    			{
	    				
	    	  			FormPropertyImpl formProperty1=(FormPropertyImpl) formProperty;
	    	  			formProperty1.setValue((String) map.get(formProperty1.getId()));
	    			}
	    			if(formProperty.getType() instanceof EnumFormType){//如果是枚举类型就取枚举值
	    				List<Map<String, Object>> enumList = new ArrayList<Map<String,Object>>();
	    				String enumId = formProperty.getId();	    				
	    				String information = formProperty.getType().getInformation("values").toString();
	    				if(!StringHelper.isEmpty(information)){
	    					information = information.substring(1, information.length()-1);	    					
	    					String[] inforArr = information.split(",");
	    					for (String info : inforArr) {
	    						Map<String, Object> enumMap = new HashMap<String, Object>();
								String[] kvArr = info.split("=");
								enumMap.put(ISystemConstant.PREDEFINED_PROCESS_ENUM_KEY,kvArr[0].trim());
								enumMap.put(ISystemConstant.PREDEFINED_PROCESS_ENUM_VALUE, kvArr[1].trim());
								enumList.add(enumMap);
							}
	    				}
	    				enumBigMap.put(enumId, enumList);
	    			}
				}
	    		taskDataMap.put(ISystemConstant.PREDEFINED_PROCESS_ENUM_TYPE_MAP, enumBigMap);  			
	  			//如果不传了jsp url，则用默认的
	  			String jspUrl = request.getParameter(ISystemConstant.PREDEFINED_JSP_URL);
	  			if(StringHelper.isEmpty(jspUrl)){
	  				return "/activiti/wk/generalbusinessprocess/taskInfo";
	  			}else{
	  				return jspUrl;
	  			}*/
	  			redirectAttributes.addFlashAttribute("message", "尚未关联外部模板!");
	        	//出错时，跳转url
	        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
	        	if(StringHelper.isEmpty(errorJspUrl)){
	        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
	        	}else{
	        		return errorJspUrl;
	        	}
	  		}else{
	  			//根据模板名称查找表单模板.模板url	  			
	  			Map<String, Object> searchPara = new HashMap<String,Object>();
	  			
	  			searchPara.put("templateName", formTemplateName);            	  		
				List<FormTemplateVo> formTemplateVos = formTemplateService.list(searchPara, null);
				if(CollectionUtils.isEmpty(formTemplateVos)){
					redirectAttributes.addFlashAttribute("message", "模板名称："+formTemplateName+"尚未定义!");
	  				//出错时，跳转url
		        	String errorJspUrl = request.getParameter(ISystemConstant.PREDEFINED_ERROR_JSP_URL);
		        	if(StringHelper.isEmpty(errorJspUrl)){
		        		return "redirect:"+CryptoHelper.encryptUrl(request,"/generalbusinessprocess/taskList");
		        	}else{
		        		return errorJspUrl;
		        	}					
				}
	  			return formTemplateVos.get(0).getTemplateHtml();
	  		}
	    }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }  		
    }
    /**
     * 完成任务
     *
     * @param id
     * @return
     * @throws Exception 
     */    
    @RequestMapping(value = "complete", 
		consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> complete(GeneralBusinessProcessVo generalBusinessProcessVo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {
    	boolean bLock = false;
    	String taskId = request.getParameter(REQUEST_ID);
    	Map<String,Object> result = new HashMap<String,Object>();
    	String procInstId="";
    	try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	    	Task task = (Task) taskService.createTaskQuery().taskId(taskId).singleResult();
	        //如果传个性化服务id		  	
	  		String serviceBeanId = request.getParameter(ISystemConstant.PREDEFINED_SERVICE_BEAN_ID);
	  		if(!StringHelper.isEmpty(serviceBeanId)){
	  			IExtGeneralBusinessProcessService  generalBusinessService = (IExtGeneralBusinessProcessService) RmBeanFactory.getBean(serviceBeanId);
	 			generalBusinessService.doSaveTaskData(request, response);  			
	  		}else{
	  			//审核意见
	  			String auditOpinion = request.getParameter(ISystemConstant.PREDEFINED_AUDIT_OPINION);
	  			if(!StringHelper.isEmpty(auditOpinion)){
	  				taskService.addComment(taskId, task.getProcessInstanceId(), auditOpinion);
	  			}
	  			procInstId = task ==null?"":task.getProcessInstanceId();
	  			Map <String ,Object> map=new HashMap();
	  			map.put("taskId", taskId);
	  			map.put("procInstId", procInstId);
//	  			map.put("", task.getProcessInstanceId());
	  			List<GeneralBusinessProcessVo> generalBusinessProcessVo1=generalBusinessProcessService.list(map, null);
	  			GeneralBusinessProcessVo generalBusinessProcessVo2=generalBusinessProcessVo1.get(0);
	  			
	  			generalBusinessProcessService.insertComplete(generalBusinessProcessVo2, taskId, request);
	  		}
				
    	} catch (Exception e) {
      	    RmProjectHelper.logError("提交流程失败(流程实例id:"+procInstId+",任务id:"+taskId+")", e);           
            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
            result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
            return result;	  		
	    }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
	    }
    	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
        result.put(ISystemConstant.AJAX_MESSAGE, "提交成功");
        return result;
    }
    /**
     * 列出当前登录人能看到所有流程实例
     */
    @RequestMapping(value = "myFlowList")
    public String myFLowList(HttpServletRequest request) {
  	  RmPageVo pageVo = RmJspHelper.transctPageVo(request, (int) repositoryService.createProcessDefinitionQuery().count());
  	  List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().desc().listPage(pageVo.getStartIndex()-1, pageVo.getPageSize());
  	  request.setAttribute("beans", list);
  	  return "/activiti/wk/listBusinessApplication";
    }    
    /**
     * 启动流程实例  
     * @param processDefinitionId
     * @param request
     * @return
     */
    @RequestMapping(value = "start", 
  			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> start(HttpServletRequest request,HttpServletResponse response) {
  	 
  	  Map<String,Object> result = new HashMap<String,Object>();
  	  
  	  	boolean bLock = false;
  	  	try{
       	  bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));    

       	    String processDefinitionId = request.getParameter(ISystemConstant.PREDEFINED_PROCESS_DEFINITION_ID);
  		    //如果传个性化服务id		  	
	  		String serviceBeanId = request.getParameter(ISystemConstant.PREDEFINED_SERVICE_BEAN_ID);
	  		if(!StringHelper.isEmpty(serviceBeanId)){
	  			IExtGeneralBusinessProcessService  generalBusinessService = (IExtGeneralBusinessProcessService) RmBeanFactory.getBean(serviceBeanId);
	  			//内部负责业务处理及调用流程启动api
	 			generalBusinessService.doSaveTaskData(request, response);  			
	  		}else{
	  			//默认处理方式：一个页面数据插入到通用流程业务表
	  			GeneralBusinessProcessVo vo = new GeneralBusinessProcessVo();
	  			vo.setParentId("");
	  			vo.setProcDefId(processDefinitionId);
	  			ProcessDefinition processDef = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
	  			if(processDef!=null){
	  				vo.setProcName(processDef.getName());
	  				vo.setProcKey(processDef.getKey());
	  			}
	  			RmUserVo userVo = RmProjectHelper.getRmUserVo(request);
	  			if(userVo!=null){
	  			//发起人	  			
	  			vo.setInitiator(userVo.getName());
	  			//发起人id
	  			vo.setInitiatorId(userVo.getId());
	  			}
	  			//发起时间
	  			vo.setInitiatorTime(DateUtil.getNowTimestamp());
	  			//组装页面数据
	  			RmPopulateHelper.populate(vo, request);
	  			//标识创建人，创建时间
	  			RmVoHelper.markCreateStamp(request, vo);
	  			
	  			generalBusinessProcessService.insert(vo);
		  		identityService.setAuthenticatedUserId(RmProjectHelper.getRmUserId(request));
		  	    ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId);
		  	    //回填流程实例id
		  	    vo.setProcInstId(processInstance.getId());
		  	    generalBusinessProcessService.update(vo);
	  		}
       
        } catch (Exception e) {
      	    RmProjectHelper.logError("启动流程失败(流程定义id:"+request.getParameter("processDefinitionId")+")", e);           
            result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
            result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
            return result;
        }finally{
  	      //最后解锁
  	      RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
        }
        
        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
        result.put(ISystemConstant.AJAX_MESSAGE, "启动成功");
        return result;
    }    
}
